import 'package:boss/ui/widget/calendar/provider/calendar_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'calendar_view.dart';

class CalendarBody extends StatefulWidget {
  @override
  _CalendarBodyState createState() => _CalendarBodyState();
}

class _CalendarBodyState extends State<CalendarBody> {
  CalendarProvider provider;

  @override
  void initState() {
    super.initState();
    provider = Provider.of<CalendarProvider>(context, listen: false);

    provider.pageController = PageController();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      provider.pageController.jumpToPage(provider.currentPageIndex);
    });
  }

  @override
  void dispose() {
    provider.pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: PageView.builder(
        physics: BouncingScrollPhysics(),
        controller: Provider.of<CalendarProvider>(context, listen: false).pageController,
        onPageChanged: (pageIndex) {
          var calendarProvider = Provider.of<CalendarProvider>(
            context,
            listen: false,
          );
          calendarProvider.setPageIndex(pageIndex);
        },
        itemBuilder: (context, index) {
          return CalendarView(
            index: index,
          );
        },
        itemCount: provider.maxPage,
      ),
    );
  }
}
